package com.example.flower_shop.controller;

import com.example.flower_shop.common.ApiResponse;
import com.example.flower_shop.dto.review.ReviewDTO;
import com.example.flower_shop.service.ReviewService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@Api(tags = "商品评论管理")
@RestController
@RequestMapping("/api/reviews")
@RequiredArgsConstructor
public class ReviewController {

    private final ReviewService reviewService;

    @ApiOperation("获取商品评论列表")
    @GetMapping("/products/{productId}")
    public ApiResponse<Page<ReviewDTO>> getProductReviews(
            @PathVariable Long productId,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("获取商品评论列表, productId: {}, page: {}, size: {}", productId, page, size);
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<ReviewDTO> reviews = reviewService.getProductReviews(productId, pageable);
            log.info("获取商品评论成功, 共{}条评论", reviews.getTotalElements());
            return ApiResponse.success(reviews);
        } catch (Exception e) {
            log.error("获取商品评论失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @ApiOperation("获取用户评论列表")
    @GetMapping("/users/{userId}")
    public ApiResponse<Page<ReviewDTO>> getUserReviews(
            @PathVariable Long userId,
            Pageable pageable) {
        return ApiResponse.success(reviewService.getUserReviews(userId, pageable));
    }

    @ApiOperation("创建商品评论")
    @PostMapping("/products/{productId}")
    public ApiResponse<ReviewDTO> createReview(
            @AuthenticationPrincipal Long userId,
            @PathVariable Long productId,
            @Valid @RequestPart ReviewDTO reviewDTO,
            @RequestPart(value = "images", required = false) List<MultipartFile> images) {
        // 检查用户是否购买过此商品
        if (reviewDTO.getOrderNo() == null || reviewDTO.getOrderNo().isEmpty()) {
            return ApiResponse.error("请提供订单编号");
        }

        // 调用服务方法创建评论
        return ApiResponse.success(reviewService.createReview(userId, productId, reviewDTO, images));
    }

    @ApiOperation("创建商品评论（JSON格式）")
    @PostMapping("/products/{productId}/json")
    public ApiResponse<ReviewDTO> createReviewJson(
            @AuthenticationPrincipal Long userId,
            @PathVariable Long productId,
            @Valid @RequestBody ReviewDTO reviewDTO) {
        // 检查用户是否购买过此商品
        if (reviewDTO.getOrderNo() == null || reviewDTO.getOrderNo().isEmpty()) {
            return ApiResponse.error("请提供订单编号");
        }

        // 记录接收到的评论数据，特别是图片URLs
        log.info("接收到JSON评论数据: userId={}, productId={}, reviewDTO={}", userId, productId, reviewDTO);
        if (reviewDTO.getImageUrls() != null) {
            log.info("评论包含{}张图片: {}", reviewDTO.getImageUrls().size(), reviewDTO.getImageUrls());
        }

        // 调用服务方法创建评论，确保传递包含imageUrls的reviewDTO
        return ApiResponse.success(reviewService.createReview(userId, productId, reviewDTO, null));
    }

    @ApiOperation("更新商品评论")
    @PutMapping("/{reviewId}")
    public ApiResponse<ReviewDTO> updateReview(
            @AuthenticationPrincipal Long userId,
            @PathVariable Long reviewId,
            @Valid @RequestPart("review") ReviewDTO reviewDTO,
            @RequestPart(value = "images", required = false) List<MultipartFile> images) {
        return ApiResponse.success(reviewService.updateReview(userId, reviewId, reviewDTO, images));
    }

    @ApiOperation("删除商品评论")
    @DeleteMapping("/{reviewId}")
    public ApiResponse<Void> deleteReview(
            @AuthenticationPrincipal Long userId,
            @PathVariable Long reviewId) {
        reviewService.deleteReview(userId, reviewId);
        return ApiResponse.success(null);
    }

    @ApiOperation("点赞评论")
    @PostMapping("/{reviewId}/like")
    public ApiResponse<Void> likeReview(
            @AuthenticationPrincipal Long userId,
            @PathVariable Long reviewId) {
        reviewService.likeReview(userId, reviewId);
        return ApiResponse.success(null);
    }

    @ApiOperation("取消点赞评论")
    @DeleteMapping("/{reviewId}/like")
    public ApiResponse<Void> unlikeReview(
            @AuthenticationPrincipal Long userId,
            @PathVariable Long reviewId) {
        reviewService.unlikeReview(userId, reviewId);
        return ApiResponse.success(null);
    }

    @GetMapping("/my")
    public ApiResponse<Page<ReviewDTO>> getMyReviews(
            @AuthenticationPrincipal Long userId,
            Pageable pageable) {
        Page<ReviewDTO> reviews = reviewService.getReviewsByUserId(userId, pageable);
        return ApiResponse.success(reviews);
    }
}